package com.dianxun.bookmanager.ui.fragment;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.dianxun.bookmanager.R;
import com.dianxun.bookmanager.common.AppKeyManager;
import com.dianxun.bookmanager.common.base.BaseFragment;
import com.dianxun.bookmanager.entity.BookDetailEntity;
import com.dianxun.bookmanager.entity.ServiceResult;
import com.dianxun.bookmanager.entity.UserListEntity;
import com.dianxun.bookmanager.net.Api;
import com.dianxun.bookmanager.net.HttpListener;
import com.dianxun.bookmanager.ui.activity.UserListActivity;
import com.dianxun.bookmanager.utils.Utils;
import com.google.zxing.integration.android.IntentIntegrator;

import java.util.Calendar;

import butterknife.BindView;

import static android.app.Activity.RESULT_OK;

/**
 * 借阅
 */
public class BorrowingFragment extends BaseFragment implements View.OnClickListener {

//    @BindView(R.id.tv_nfc)
//    TextView tv_nfc;
    @BindView(R.id.tv_scan)
    TextView tv_scan;
    @BindView(R.id.tv_rfid)
    TextView tv_rfid;
    @BindView(R.id.layout_user)
    RelativeLayout layout_user;
    @BindView(R.id.tv_user_detail)
    TextView tv_user_detail;
    @BindView(R.id.tv_book_detail)
    TextView tv_book_detail;
    @BindView(R.id.tv_lenddate)
    TextView tv_lenddate;
    @BindView(R.id.tv_expectreturndate)
    TextView tv_expectreturndate;
    @BindView(R.id.tv_save_bookrecord)
    TextView tv_save_bookrecord;
    private String userId;
    private String userName;
    private String bookId;
    private Calendar lendDateCalendar;
    private String lendDate;
    private Calendar expectReturnDateCalendar;
    private String expectReturnDate;
    public ProgressDialog nfcProgressDialog;
    public ProgressDialog rfidProgressDialog;

    @Override
    protected int getContentView() {
        return R.layout.fragment_borrowing;
    }

    @Override
    protected void initView() {
        lendDateCalendar = Calendar.getInstance();
        expectReturnDateCalendar = Calendar.getInstance();
        expectReturnDateCalendar.add(Calendar.DAY_OF_MONTH, 7);
        lendDate = Utils.getTimeString(lendDateCalendar.getTimeInMillis());
        expectReturnDate = Utils.getTimeString(expectReturnDateCalendar.getTimeInMillis());
        tv_lenddate.setText(lendDate);
        tv_expectreturndate.setText(expectReturnDate);
    }

    @Override
    protected void initListeners() {
//        tv_nfc.setOnClickListener(this);
        tv_scan.setOnClickListener(this);
        tv_rfid.setOnClickListener(this);
        layout_user.setOnClickListener(this);
        tv_lenddate.setOnClickListener(this);
        tv_expectreturndate.setOnClickListener(this);
        tv_save_bookrecord.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        DatePickerDialog datePicker;
        switch (v.getId()) {
//            case R.id.tv_nfc:
//                if (checkNFC()) {
//                    nfcProgressDialog = new ProgressDialog(mContext);
//                    nfcProgressDialog.setTitle("请扫描手环");
//                    nfcProgressDialog.show();
//                }
//                break;
            case R.id.tv_scan:
                if (Utils.getSystemModel().equals("PDA")) {
                    final AlertDialog alertDialog = new AlertDialog.Builder(mContext).setTitle("请扫描条码")
                            .setNegativeButton("取消", null).create();
                    LayoutInflater factory = LayoutInflater.from(mContext);
                    final View view = factory.inflate(R.layout.layout_scan_edit, null);
                    final EditText edittext = view.findViewById(R.id.editText);
                    edittext.setOnTouchListener(new View.OnTouchListener() {
                        @Override
                        public boolean onTouch(View v, MotionEvent event) {
                            return true;
                        }
                    });
                    edittext.addTextChangedListener(new TextWatcher() {
                        @Override
                        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                        }

                        @Override
                        public void onTextChanged(CharSequence s, int start, int before, int count) {

                        }

                        @Override
                        public void afterTextChanged(Editable s) {
                            String barNo = edittext.getText().toString();
                            getBookInfoByBarNo(barNo);
                            if (alertDialog != null && alertDialog.isShowing()) {
                                alertDialog.cancel();
                            }
                        }
                    });
                    alertDialog.setView(view);
                    alertDialog.show();
                } else {
                    IntentIntegrator integrator = new IntentIntegrator(getActivity());
                    integrator.setOrientationLocked(false);
                    integrator.initiateScan();
                }
                break;
            case R.id.tv_rfid:
                if (checkNFC()) {
                    rfidProgressDialog = new ProgressDialog(mContext);
                    rfidProgressDialog.setTitle("请读取RFID标签");
                    rfidProgressDialog.show();
                }
                break;
            case R.id.layout_user:
                Api.getUserList(mContext, new HttpListener<ServiceResult>() {
                    @Override
                    public void onSucceed(ServiceResult response) {
                        if (response.getCode() != null && response.getCode().equals("1")) {
                            Bundle b = new Bundle();
                            b.putSerializable(AppKeyManager.EXTRA_ENTITY, response);
                            jumpActivityForResult(AppKeyManager.REQUEST_USERLIST, UserListActivity.class, b);
                        } else {
                            toast(response.getMessage());
                        }
                    }

                    @Override
                    public void onFailed() {

                    }
                }, UserListEntity.class);
                break;
            case R.id.tv_lenddate:
                datePicker = new DatePickerDialog(mContext, new DatePickerDialog.OnDateSetListener() {

                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear,
                                          int dayOfMonth) {
                        lendDateCalendar.set(year, monthOfYear, dayOfMonth);
                        lendDate = Utils.getTimeString(lendDateCalendar.getTimeInMillis());
                        tv_lenddate.setText(lendDate);
                    }
                }, lendDateCalendar.get(Calendar.YEAR), lendDateCalendar.get(Calendar.MONTH), lendDateCalendar.get(Calendar.DAY_OF_MONTH));
                datePicker.show();
                break;
            case R.id.tv_expectreturndate:
                datePicker = new DatePickerDialog(mContext, new DatePickerDialog.OnDateSetListener() {

                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear,
                                          int dayOfMonth) {
                        expectReturnDateCalendar.set(year, monthOfYear, dayOfMonth);
                        expectReturnDate = Utils.getTimeString(expectReturnDateCalendar.getTimeInMillis());
                        tv_expectreturndate.setText(expectReturnDate);
                    }
                }, expectReturnDateCalendar.get(Calendar.YEAR), expectReturnDateCalendar.get(Calendar.MONTH), expectReturnDateCalendar.get(Calendar.DAY_OF_MONTH));
                datePicker.show();
                break;
            case R.id.tv_save_bookrecord:
                if (TextUtils.isEmpty(bookId)) {
                    toast("请扫描图书");
                    return;
                }
                if (TextUtils.isEmpty(userId)) {
                    toast("无借书人信息");
                    return;
                }
                Api.savebookRecord(mContext, bookId, userId, userName, lendDate, expectReturnDate,
                        new HttpListener<ServiceResult>() {
                            @Override
                            public void onSucceed(ServiceResult response) {
                                if (response.getCode() != null && response.getCode().equals("1")) {
                                    toast("借阅成功");
                                    userId = null;
                                    userName = null;
                                    bookId = null;
                                    tv_user_detail.setText("");
                                    tv_book_detail.setText("");
                                } else {
                                    toast(response.getMessage());
                                }
                            }

                            @Override
                            public void onFailed() {

                            }
                        }, ServiceResult.class);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == AppKeyManager.REQUEST_USERLIST && resultCode == RESULT_OK) {
            UserListEntity.UserListBean bean = (UserListEntity.UserListBean) data.getExtras().getSerializable(AppKeyManager.EXTRA_ENTITY);
            tv_user_detail.setText("姓名：" + bean.getUserName() + "\n"
                    + "性别：" + bean.getSex());
            userId = bean.getUserId();
            userName = bean.getUserName();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public void getBookInfoByRfidNo(String rfidNo) {
        if (rfidProgressDialog != null && rfidProgressDialog.isShowing()) {
            rfidProgressDialog.dismiss();
            rfidProgressDialog = null;
        }
        Api.getBookInfoByRfidNo(mContext, rfidNo, new HttpListener<ServiceResult>() {
            @Override
            public void onSucceed(ServiceResult response) {
                if (response.getCode() != null && response.getCode().equals("1")) {
                    BookDetailEntity.DataInfoBean entity = ((BookDetailEntity) response).getDataInfo();
                    if (entity.getFlag() == AppKeyManager.TYPE_BOOKLIB_OUT) {
                        toast("该图书已出借，请核查！");
                        return;
                    }
                    tv_book_detail.setText("书名：" + entity.getBookName() + "\n"
                            + "作者：" + entity.getAuthor() + "\n"
                            + "出版社：" + entity.getPress() + "\n"
                            + "出版日期：" + entity.getPublishDate());
                    bookId = entity.getBookId();
                } else {
                    toast(response.getMessage());
                }
            }

            @Override
            public void onFailed() {

            }
        }, BookDetailEntity.class);
    }

    public void getBookInfoByBarNo(String barNo) {
        // "T00004"
        Api.getBookInfoByBarNo(mContext, barNo, new HttpListener<ServiceResult>() {
            @Override
            public void onSucceed(ServiceResult response) {
                if (response.getCode() != null && response.getCode().equals("1")) {
                    BookDetailEntity.DataInfoBean entity = ((BookDetailEntity) response).getDataInfo();
                    tv_book_detail.setText("书名：" + entity.getBookName() + "\n"
                            + "作者：" + entity.getAuthor() + "\n"
                            + "出版社：" + entity.getPress() + "\n"
                            + "出版日期：" + entity.getPublishDate());
                    bookId = entity.getBookId();
                } else {
                    toast(response.getMessage());
                }
            }

            @Override
            public void onFailed() {

            }
        }, BookDetailEntity.class);
    }
}
